import 'dart:convert';
import 'package:lib_database/src/model/integral_model/integral_model.dart';
import 'package:lib_database/src/model/fans_model/fans_model.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:lib_database/src/network.dart';
import 'dart:math';


class SP {
  SP._privateConstructor();

  static final SP _instance = SP._privateConstructor();

  factory SP() {
    return _instance;
  }

  late final SharedPreferences _prefs;

  init() async {
    _prefs = await SharedPreferences.getInstance();
    // final localSalt = getRandomSalt();
    // if (localSalt == null) {
    //   setRandomSalt(generateRandomSalt());
    // }
  }

  String generateRandomSalt() {
    const chars = '0123456789';
    final random = Random();
    String randomString = String.fromCharCodes(Iterable.generate(
      8,
      (_) => chars.codeUnitAt(random.nextInt(chars.length)),
    ));
    return randomString;
  }

  static const String keyAppLoginInfo = 'app_login_info';

  static const String keyChainsList = 'key_chain_list';

  static const String keyTokensList = 'key_token_list';

  static const String keyLocalTheme = 'current_wallet_theme';

  static const String keyCurrentWalletInfoId = 'current_wallet_info_id';
  static const String keyWalletSelectedWalletInfoId = 'wallet_selected_wallet_info_id';
  static const String keyWalletIdSortList = 'wallet_id_sort_list';
  static const String keyDAppIndexList = 'dapp_index_list';
  static const String keyOtcPairIndexList = 'otc_pair_index_list';
  static const String keyOtcBannerIndexList = 'otc_banner_index_list';
  static const String keyOtcCachedDepthData = 'otc_cached_depth_pair_id_';
  static const String keyLastShowLimitDialogWhich24h = 'last_show_limit_dialog_which_24h';
  static const String keyGoNativeDexMarket = 'go_native_dex_market';
  static const String keySaltInApp = 'salt_in_app';
  static const String keyGetAssetsShowState = 'kai_assets_show_state_';
  static const String keySigninList = 'sign_in_list';

  // ----------------------- 积分 签到 信息 ----------------------------
  static const String keyIntegralSignIn = 'key_integral_sign_in_';
  static const String keyTasksSignIn = 'key_tasks_';
  static const String keyFansOrFollowSignIn = 'key_FF_';
  static const String keyTaskIndex = 'key_tasks_index_';

  String? getRandomSalt() {
    return _prefs.getString(keySaltInApp);
  }

  setRandomSalt(String salt) {
    return _prefs.setString(keySaltInApp, salt);
  }

  /**
   * 存储 task 任务 信息
   */
  int? getTaskIndex() {
    return _prefs.getInt(keyTaskIndex);
  }

  setTaskIndex(int index,String uId) {
    return _prefs.setInt(keyTaskIndex+ uId.toString(), index);
  }


  /**
   * 存储 fans 信息
   */
  Future<bool> setFansListData(List<FansTabsItemDataType> lists, String uId) async {
    try {
      var result = [...lists].map((e) {
        return e.toString();
      });
      print('sp（） setFansListData   $result');
      bool yes = await _prefs.setStringList(keyFansOrFollowSignIn + uId.toString(), result.toList());
      return yes;
    } catch (e) {
      return false;
    }
  }

  List<FansTabsItemDataType> getFansListData(String uId) {
    List<FansTabsItemDataType> result = [];
    try {
      var lists = _prefs.getStringList(keyFansOrFollowSignIn + uId.toString());
      if (lists != null) {
        for (var i = 0; i < lists.length; i++) {
          dynamic item = lists[i];
          if(lists[i].runtimeType == String){
            item = jsonDecode(lists[i]);
          }
          result.add(FansTabsItemDataType(
              title: item['title'],
              icon: item['icon'],
              userId: item['userId'],
              isFriend: item['isFriend'],
              describe: item['describe'],
              status: item['status']));
        }
      }
      return result;
    } catch (e) {
      return result;
    }
  }

  /**
   * 存储 task 任务 信息
   */
  Future<bool> setTaskSignInData(List<IntegralTabsItemDataType> lists, String uId) async {
    try {
      var result = [...lists].map((e) {
        return e.toString();
      });
      print('sp() setTaskSignInData  $result');
      bool yes = await _prefs.setStringList(keyTasksSignIn + uId.toString(), result.toList());
      return yes;
    } catch (e) {
      return false;
    }
  }

  List<IntegralTabsItemDataType> getTaskSignInData(String uId) {
    List<IntegralTabsItemDataType> result = [];
    try {
      var lists = _prefs.getStringList(keyTasksSignIn + uId.toString());
      if (lists != null) {
        for (var i = 0; i < lists.length; i++) {
          dynamic item = lists[i];
          if(lists[i].runtimeType == String){
            item = jsonDecode(lists[i]);
          }
          result.add(IntegralTabsItemDataType(
              title: item['title'],
              icon: item['icon'],
              task_id: item['task_id'],
              task_code: item['task_code'].runtimeType == String? int.parse(item['task_code']):item['task_code'],
              describe: item['describe'],
              score: item['score'].runtimeType == String? int.parse(item['score']):item['score'],
              status: item['status']));
        }
      }
      return result;
    } catch (e) {
      return result;
    }
  }

  /**
   * 存储 积分 签到 信息
   */
  Future<bool> setIntegralSignInData(List<SignInItemType> lists, String uId) async {
    try {
      var result = [...lists].map((e) {
        return e.toString();
      });
      print('sp() setIntegralSignInData  $result');
      bool yes = await _prefs.setStringList(keyIntegralSignIn + uId.toString(), result.toList());
      return yes;
    } catch (e) {
      return false;
    }
  }

  List<SignInItemType> getIntegralSignInData(String uId) {
    List<SignInItemType> result = [];
    try {
      var lists = _prefs.getStringList(keyIntegralSignIn + uId.toString());
      if (lists != null) {
        for (var i = 0; i < lists.length; i++) {
          dynamic item = jsonDecode(lists[i]);
          result.add(SignInItemType(
            amount: item['amount'],
            isNormal: item['isNormal'],
            isSignIn: item['isSignIn'],
            date: item['date'],
          ));
        }
      }
      return result;
    } catch (e) {
      return result;
    }
  }

  /**
   * 存储 主链 网络 信息
   */
  Future<bool> setKeyChainsList(List<Chain> chainLists) async {
    try {
      var result = [...chainLists].map((e) {
        return e.toString();
      });
      bool yes = await _prefs.setStringList(keyChainsList, result.toList());
      return yes;
    } catch (e) {
      return false;
    }
  }

  List<Chain> getKeyChainsList() {
    List<Chain> result = [];
    try {
      var chainsLists = _prefs.getStringList(keyChainsList);
      if (chainsLists != null) {
        for (var i = 0; i < chainsLists.length; i++) {
          dynamic item = jsonDecode(chainsLists[i]).map<String, dynamic>((key, value) {
            return MapEntry(key.toString(), value);
          });
          List<String> rpcList = [];
          dynamic evmInfo = item['evmInfo'];
          for (var j = 0; j < evmInfo['rpcList'].length; j++) {
            var it = evmInfo['rpcList'][j];
            rpcList.add(it);
          }
          ChainType type= ChainType.eth;
          print('item["type"] ::::: ${item['type']}');
          if(item['type'].indexOf("tron")>-1){
            type = ChainType.tron;
          }
          if(item['type'].indexOf("sol")>-1){
            type = ChainType.sol;
          }
          result.add(Chain(
              type: type,
              name: item['name'],
              shortName: item['shortName'],
              symbol: item['symbol'],
              logo: item['logo'],
              derivePath: item['derivePath'],
              blockExplorerUrl: item['blockExplorerUrl'],
              blockExplorerApi: item['blockExplorerApi'],
              evmInfo: EVMInfo(chainId: evmInfo['chainId'], rpcList: rpcList)));
        }
      }
      return result;
    } catch (e) {
      return result;
    }
  }

  /**
   * 存储每月签到信息
   */
  Future<bool> setSigninList(List<SignInData> signinLists, String uid, String date) async {
    try {
      var result = [...signinLists].map((e) {
        return e.toString();
      });
      bool yes = await _prefs.setStringList(keySigninList + uid + date, result.toList());
      return yes;
    } catch (e) {
      return false;
    }
  }

  List<SignInData> getSigninList(String uid, String date) {
    List<SignInData> result = [];
    try {
      var signinLists = _prefs.getStringList(keySigninList + uid + date);
      if (signinLists != null) {
        for (var i = 0; i < signinLists.length; i++) {
          dynamic item = jsonDecode(signinLists[i]);
          result.add(SignInData(
            start: item['start'],
            days: item['days'],
          ));
        }
      }
      return result;
    } catch (e) {
      return result;
    }
  }

  /**
   * 存储 网络 获取的代币 信息
   */
  Future<bool> setKeyTokenList(List<String> tokenList) async {
    bool yes = await _prefs.setStringList(keyTokensList, tokenList);
    return yes;
  }

  List<dynamic> getKeyTokenList() {
    var tokenLists = _prefs.getStringList(keyTokensList);
    return tokenLists ?? [];
  }

  /**
   * 存储 用户 token
   */
  Future<bool> setAppLoginInfo(Map<String, String> loginInfo) async {
    bool yes = await _prefs.setString(keyAppLoginInfo, loginInfo.toString());
    return yes;
  }

  Object getAppLoginInfo() {
    var loginInfo = _prefs.getString(keyAppLoginInfo);
    return loginInfo != null ? loginInfo : {};
  }

  /**
   * 访问网站提示
   */
  static const String keyBrowswerInsideValid = 'browser_inside_valid';

  List<String> getBrowserInsideValid() {
    var list = _prefs.getStringList(keyBrowswerInsideValid);
    return list ?? [];
  }

  Future<bool> setBrowserInsideValid(List<String> list) async {
    bool yes = await _prefs.setStringList(keyBrowswerInsideValid, list);
    return yes;
  }

  /**
   * 收藏提示
   */
  static const String favoriteStatusList = 'favorite_status_List';

  List<String> getFavoriteStatusList() {
    var list = _prefs.getStringList(favoriteStatusList);
    return list ?? [];
  }

  Future<bool> setFavoriteStatusList(List<String> list) async {
    bool yes = await _prefs.setStringList(favoriteStatusList, list);
    return yes;
  }

  /**
   * 取消收藏提示
   */
  static const String cancelFavoriteStatusList = 'cancel_favorite_status_List';

  List<String> getCancelStatusList() {
    var list = _prefs.getStringList(cancelFavoriteStatusList);
    return list ?? [];
  }

  Future<bool> setCancelStatusList(List<String> list) async {
    bool yes = await _prefs.setStringList(cancelFavoriteStatusList, list);
    return yes;
  }

  /**
   * Banner列表
   */
  static const String dappBannerList = 'dapp_banner_List';

  Map<String, dynamic> getDappBannerList() {
    String? jsonString = _prefs.getString(dappBannerList);
    // 将数组字符串反序列化为数组对象
    Map<String, dynamic> list = jsonString != null ? jsonDecode(jsonString) : {};
    return list;
  }

  Future<bool> setDappBannerList(Map<String, dynamic> bannerData) async {
    String jsonString = jsonEncode(bannerData);
    bool yes = await _prefs.setString(dappBannerList, jsonString);
    return yes;
  }

  /**
   * 展示用户 资产 是否显示
   */

  bool getAssetsShowState(String uid) {
    bool? assetsState = _prefs.getBool(keyGetAssetsShowState + uid.toString());
    return assetsState ?? true;
  }

  setAssetsShowState(String uid, bool assetsState) {
    _prefs.setBool(keyGetAssetsShowState + uid.toString(), assetsState);
  }

  /**
   * Hot列表
   */
  static const String dappHotData = 'dapp_Hot_Data';

  Map<String, dynamic> getDappHotData() {
    String? jsonString = _prefs.getString(dappHotData);
    // 将数组字符串反序列化为数组对象
    Map<String, dynamic> list = jsonString != null ? jsonDecode(jsonString) : {};
    return list;
  }

  Future<bool> setDappHotData(Map<String, dynamic> bannerData) async {
    String jsonString = jsonEncode(bannerData);
    bool yes = await _prefs.setString(dappHotData, jsonString);
    return yes;
  }

  String getLocalTheme() {
    String theme = _prefs.getString(keyLocalTheme) ?? 'light';
    return theme;
  }

  setLocalTheme(String theme) {
    return _prefs.setString(keyLocalTheme, theme);
  }

  String getCurrentWalletInfoId() {
    String? walletInfoId = _prefs.getString(keyCurrentWalletInfoId);
    return walletInfoId ?? '0';
  }

  setCurrentWalletInfoId(String walletInfoId) {
    _prefs.setString(keyCurrentWalletInfoId, walletInfoId);
  }

  int getWalletSelectedInfoId(int walletId) {
    int? walletInfoId = _prefs.getInt(keyWalletSelectedWalletInfoId + walletId.toString());
    return walletInfoId ?? 0;
  }

  setWalletSelectedInfoId(int walletId, int walletInfoId) {
    _prefs.setInt(keyWalletSelectedWalletInfoId + walletId.toString(), walletInfoId);
  }

  String getWalletSortIdList() {
    return _prefs.getString(keyWalletIdSortList) ?? '';
  }

  setWalletSortIdList(String data) {
    return _prefs.setString(keyWalletIdSortList, data);
  }

  String? getDAppIndex() {
    return _prefs.getString(keyDAppIndexList);
  }

  setDAppIndex(String data) {
    return _prefs.setString(keyDAppIndexList, data);
  }

  String? getOtcPairIndexList() {
    return _prefs.getString(keyOtcPairIndexList);
  }

  setOtcPairIndexList(String data) {
    return _prefs.setString(keyOtcPairIndexList, data);
  }

  String? getOtcBannerIndexList() {
    return _prefs.getString(keyOtcBannerIndexList);
  }

  setOtcBannerIndexList(String data) {
    return _prefs.setString(keyOtcBannerIndexList, data);
  }

  String? getOtcCachedDepthData(int pairId) {
    return _prefs.getString(keyOtcCachedDepthData + pairId.toString());
  }

  setOtcCachedDepthData(int pairId, String data) {
    return _prefs.setString(keyOtcCachedDepthData + pairId.toString(), data);
  }

  int getLastShowLimitDialogWhich24h() {
    return _prefs.getInt(keyLastShowLimitDialogWhich24h) ?? 0;
  }

  setLastShowLimitDialogWhich24h(int time) {
    return _prefs.setInt(keyLastShowLimitDialogWhich24h, time);
  }

  bool goNativeMarket() {
    return _prefs.getBool(keyGoNativeDexMarket) ?? false;
  }

  setGoNativeMarket(bool go) {
    _prefs.setBool(keyGoNativeDexMarket, go);
  }
}
